package com.example.androidwearmap;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;

import org.apache.http.HttpRequest;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2015/7/10.
 */
public class GpsService extends Service implements LocationListener {

    Location location = null; // location
    LocationManager locationManager;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled=false;
    int FORE_ID = 1335;

    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
    // The minimum time between updates in milliseconds
    final long MIN_TIME_BW_UPDATES = 1000; // 1 minute
    String msg = "CAUTION! If kept open, can consume lots of battery";

    private Intent broadIntent = new Intent("com.example.androidwearmap.RECEIVER");
    @SuppressLint("NewApi")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent noty_intent = new Intent(this,
                com.example.androidwearmap.MainActivity.class);
        noty_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, noty_intent,
                0);
        Notification n = new Notification.Builder(this)
                .setContentTitle("GPS Serice is running...")
                .setContentText(msg).setSmallIcon(R.drawable.common_signin_btn_icon_dark)
                .setContentIntent(pIntent).setAutoCancel(true).setOngoing(true)
                .build();
        startForeground(FORE_ID, n);
        locationManager = (LocationManager) this
                .getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(isNetworkEnabled){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            if(locationManager!=null){
                location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if(location!=null){
                    latitude=location.getLatitude();
                    longitude=location.getLongitude();
                }
            }
        }
        if (!isGPSEnabled) {
        } else {
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        Toast.makeText(this,
                                "Location Listener on GPS started...",
                                Toast.LENGTH_SHORT).show();
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

        return (START_STICKY);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        if (locationManager != null) {
            locationManager.removeUpdates((LocationListener) this);
            locationManager = null;
        }
        stopForeground(true);
        Toast.makeText(this, "Location Listener on GPS Stopped...",
                Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }
    @Override
    public void onLocationChanged(Location location) {
        Log.e("GpsService", "lll:" + location.getLatitude() + "," + location.getLongitude());
        broadIntent.putExtra("latitude",location.getLatitude());
        broadIntent.putExtra("longitude", location.getLongitude());
        //记录位置信息
         uploadCurrPostion(location);
        sendBroadcast(broadIntent);
    }

    private void uploadCurrPostion(final Location location) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("uid","test");
        params.addBodyParameter("lt",String.valueOf(location.getLatitude()));
        params.addBodyParameter("lg",String.valueOf(location.getLongitude()));
        HttpUtils http=new HttpUtils();
        http.send(com.lidroid.xutils.http.client.HttpRequest.HttpMethod.GET, "http://api.o2olg.com/usercenter/station/sendLocation", params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                LogUtils.e("上传成功:"+location.getLatitude()+","+location.getLongitude());
            }

            @Override
            public void onFailure(HttpException e, String s) {
                 LogUtils.e(s,e);
            }
        });
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
